# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    def action_get_pre_account(self):
        self.ensure_one()
        lines = self.invoice_line_ids
        pre_accounts = lines.mapped('pre_account_line_id')
        if not pre_accounts:
            return
        pre_accounts_ids = [i.id for i in pre_accounts]
        domain = [('id', 'in',  pre_accounts_ids)]
        tree = self.env.ref('nd_account.NDPreAccountLineViewTree')
        form = self.env.ref('nd_account.NDPreAccountLineViewFORM')
        action = {
                'type': 'ir.actions.act_window',
                'views': [(tree.id, 'tree'), (form.id, 'form')],
                'view_mode': 'tree,form',
                'name': _('预发票明细'),
                'res_model': 'pre.account.line',
                'domain': domain
            }
        return action

    def action_get_sale(self):
        self.ensure_one()
        lines = self.invoice_line_ids
        if not lines:
            return
        pre_accounts = lines.mapped('pre_account_line_id')
        if not pre_accounts:
            return
        sale_lines = pre_accounts.mapped('sale_line_id')
        if not sale_lines:
            return
        sale_orders = sale_lines.mapped('order_id')
        if not sale_orders:
            return
        domain = [('id', 'in',  sale_orders.ids)]
        tree = self.env.ref('sale.view_quotation_tree_with_onboarding')
        form = self.env.ref('sale.view_order_form')
        action = {
            'type': 'ir.actions.act_window',
            'views': [(tree.id, 'tree'), (form.id, 'form')],
            'view_mode': 'tree,form',
            'name': _('销售订单'),
            'res_model': 'sale.order',
            'domain': domain
        }
        return action

    def action_get_purchase(self):
        self.ensure_one()
        lines = self.invoice_line_ids
        if not lines:
            return
        pre_accounts = lines.mapped('pre_account_line_id')
        if not pre_accounts:
            return
        purchase_lines = pre_accounts.mapped('purchase_line_id')
        if not purchase_lines:
            return
        purchase_orders = purchase_lines.mapped('order_id')
        if not purchase_orders:
            return
        domain = [('id', 'in', purchase_orders.ids)]
        tree = self.env.ref('purchase.purchase_order_tree')
        form = self.env.ref('purchase.purchase_order_form')
        action = {
            'type': 'ir.actions.act_window',
            'views': [(tree.id, 'tree'), (form.id, 'form')],
            'view_mode': 'tree,form',
            'name': _('采购订单'),
            'res_model': 'purchase.order',
            'domain': domain
        }
        return action

